"""
KidsBuddy 1.0 监督执行流程主程序
整合硬件执行流程、监督循环和时序数据记录
"""

import asyncio
import signal
import sys
import time
import os
from loguru import logger
from typing import Optional

from .config.logging import setup_logging
from .config.settings import LOOP_INTERVALS, LOG_DIR

from .core.hardware_state_machine import HardwareStateMachine
from .core.supervision_manager import SupervisionManager
from .data.time_series_recorder import TimeSeriesRecorder, TimestampedData


class KidsBuddySupervisionSystem:
    """KidsBuddy监督系统主类"""
    
    def __init__(self):
        # 核心组件
        self.hardware_state_machine = HardwareStateMachine()
        self.supervision_manager = SupervisionManager(self.hardware_state_machine)
        self.time_series_recorder = TimeSeriesRecorder()
        
        # 系统状态
        self._running = False
        self._current_session_id: Optional[str] = None
        
        # 配置信号处理
        self._setup_signal_handlers()
    
    def _setup_signal_handlers(self):
        """设置信号处理器"""
        def signal_handler(signum, frame):
            logger.info(f"Received signal {signum}, shutting down...")
            asyncio.create_task(self.shutdown())
        
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
    
    async def start(self, student_id: str = "student_001", camera_source: int = 0):
        """启动监督系统"""
        if self._running:
            logger.warning("System already running")
            return
        
        logger.info("Starting KidsBuddy Supervision System")
        
        try:
            # 启动硬件状态机
            hardware_task = asyncio.create_task(self.hardware_state_machine.start())
            
            # 启动时序数据记录器
            await self.time_series_recorder.start_recording()
            
            # 生成会话ID
            session_id = f"session_{student_id}_{int(time.time())}"
            self._current_session_id = session_id
            
            # 启动监督管理器
            success = await self.supervision_manager.start_supervision(session_id, camera_source)
            
            if not success:
                logger.error("Failed to start supervision")
                await self.shutdown()
                return
            
            self._running = True
            logger.info(f"System started successfully with session: {session_id}")
            
            # 开始数据记录循环
            await self._start_data_recording_loop(student_id)
            
            # 等待硬件状态机任务
            await hardware_task
            
        except Exception as e:
            logger.error(f"Failed to start system: {e}")
            await self.shutdown()
    
    async def shutdown(self):
        """关闭监督系统"""
        if not self._running:
            return
        
        logger.info("Shutting down KidsBuddy Supervision System")
        
        self._running = False
        
        try:
            # 停止监督管理器
            await self.supervision_manager.stop_supervision()
            
            # 停止时序数据记录器
            await self.time_series_recorder.stop_recording()
            
            # 停止硬件状态机
            await self.hardware_state_machine.stop()
            
            # 生成最终报告
            if self._current_session_id:
                await self._generate_session_report()
            
            logger.info("System shutdown completed")
            
        except Exception as e:
            logger.error(f"Error during shutdown: {e}")
    
    async def _start_data_recording_loop(self, student_id: str):
        """启动数据记录循环"""
        logger.info("Starting data recording loop")
        
        # 从配置获取记录间隔
        record_interval = LOOP_INTERVALS.get('data_record', 30.0)
        
        while self._running:
            try:
                # 收集监督统计数据
                stats = self.supervision_manager.get_supervision_statistics()
                
                if stats and self._current_session_id:
                    # 记录监督状态数据
                    await self.time_series_recorder.record_data(
                        TimestampedData(
                            timestamp=time.time(),
                            session_id=self._current_session_id,
                            student_id=student_id,
                            data_type="supervision_stats",
                            data_value=stats,
                            confidence=1.0,
                            source_device="supervision_manager"
                        )
                    )
                
                # 记录硬件状态
                hardware_state = self.hardware_state_machine.get_state_info()
                await self.time_series_recorder.record_data(
                    TimestampedData(
                        timestamp=time.time(),
                        session_id=self._current_session_id,
                        student_id=student_id,
                        data_type="hardware_state",
                        data_value=hardware_state,
                        confidence=1.0,
                        source_device="hardware_state_machine"
                    )
                )
                
                # 使用配置中的记录间隔
                await asyncio.sleep(record_interval)
                
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Data recording loop error: {e}")
                await asyncio.sleep(5.0)
    
    async def _generate_session_report(self):
        """生成会话报告"""
        try:
            logger.info(f"Generating session report for: {self._current_session_id}")
            
            # 获取会话统计
            session_stats = self.time_series_recorder.get_session_statistics(self._current_session_id)
            supervision_stats = self.supervision_manager.get_supervision_statistics()
            
            # 合并统计信息
            report = {
                "session_id": self._current_session_id,
                "generated_at": time.time(),
                "session_statistics": session_stats,
                "supervision_statistics": supervision_stats,
                "hardware_final_state": self.hardware_state_machine.get_state_info()
            }
            
            # 保存报告（这里可以扩展为保存到文件或发送到服务器）
            logger.info(f"Session report generated: {report}")
            
        except Exception as e:
            logger.error(f"Failed to generate session report: {e}")
    
    def get_system_status(self) -> dict:
        """获取系统状态"""
        return {
            "running": self._running,
            "current_session": self._current_session_id,
            "supervision_active": self.supervision_manager.is_supervision_active(),
            "hardware_state": self.hardware_state_machine.get_state_info(),
            "supervision_stats": self.supervision_manager.get_supervision_statistics() if self._running else {}
        }


async def main(student_id: str = "test_student", camera_source: int = 0):
    """主函数"""
    # 配置日志
    setup_logging()
    
    # 创建系统实例
    system = KidsBuddySupervisionSystem()
    
    try:
        # 启动系统
        await system.start(student_id=student_id, camera_source=camera_source)
        
    except KeyboardInterrupt:
        logger.info("Received keyboard interrupt")
    except Exception as e:
        logger.error(f"System error: {e}")
    finally:
        await system.shutdown()


if __name__ == "__main__":
    # 导入并使用命令行入口点
    from .__main__ import main as cli_main
    cli_main()
